package com.qdxwx.manage.controller.document;

import com.qdxwx.common.annotation.Permissions;
import com.qdxwx.common.config.UploadConfig;
import com.qdxwx.common.json.AjaxResult;
import com.qdxwx.common.upload.UploadUtils;
import com.qdxwx.common.utils.FileUtils;
import com.qdxwx.common.utils.ImageUtils;
import com.qdxwx.common.utils.TKConvert;
import com.qdxwx.common.utils.TKString;
import com.qdxwx.data.service.approal.ApproalService;
import com.qdxwx.data.service.category.CategoryService;
import com.qdxwx.data.service.document.DocumentService;
import com.qdxwx.data.service.member.MemberTypeService;
import com.qdxwx.manage.annotation.Log;
import com.qdxwx.manage.controller.BaseController;

import com.qdxwx.manage.support.SessionUtils;
import com.qdxwx.models.category.Category;
import com.qdxwx.models.document.Document;
import com.qdxwx.models.document.DocumentDetail;
import com.qdxwx.models.enums.BusinessType;
import com.qdxwx.models.enums.DocumentType;
import com.qdxwx.models.enums.ModuleType;
import com.qdxwx.models.manager.Manager;
import com.qdxwx.models.member.MemberType;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import jakarta.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * 文库修改操作 Controller
 * Qdx NetSchool Platform
 * @author qdxwx
 * @updateTime 2022/5/25
 * @description
 */
@Controller
@RequestMapping("/document")
public class DocumentEditController extends BaseController {

    @Autowired
    private DocumentService documentService;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private MemberTypeService memberTypeService;
    @Autowired
    private ApproalService approalService;

    @Permissions("document:edit")
    @GetMapping("/add.html")
    public String add(ModelMap mmap) {
        MemberType memberType = new MemberType();
        memberType.setStatus(0);
        List<MemberType> members = memberTypeService.getList(memberType,null);
        mmap.put("types", DocumentType.values());
        mmap.put("members", members);
        return "document/document-add";
    }

    @Permissions("document:edit")
    @PostMapping("/add.json")
    @Log(title = "新增资料保存", businessType = BusinessType.INSERT)
    @ResponseBody
    public AjaxResult add(HttpServletRequest request) {
        Manager manager = SessionUtils.getManager();
        if(manager == null) return error("登录超时");
        int categoryId = TKConvert.toInteger(request.getParameter("categoryId"));
        if (categoryId < 1) return error("请选择类别");
        Category category = categoryService.get(categoryId);
        if (category == null) return error("类别categoryId有误");
        String fileUrl = TKString.trim(request.getParameter("fileUrl"));
        if (TKString.isEmpty(fileUrl)) return error("请输入文件地址或上传");
        String title = TKString.trim(request.getParameter("title"));
        if (TKString.isEmpty(title)) return error("请输入文件名");
        String cover = TKString.trim(request.getParameter("cover"));
        if (TKString.isEmpty(cover)) return error("请输入封面地址或上传");
        String intro = TKString.trim(request.getParameter("intro"));
        if (TKString.isEmpty(intro)) return error("请输入资料简介");
        DocumentDetail document = new DocumentDetail();
        document.setCompanyId(manager.getCompanyId());
        document.setChannelId(11);
        document.setCategoryId(category.getCategoryId());
        document.setCategoryName(category.getCategoryName());
        document.setSubjectId(category.getSubjectId());
        document.setTypeId(TKConvert.toInteger(request.getParameter("typeId")));
        document.setTitle(title);
        document.setTags(TKString.trim(request.getParameter("tags")));
        document.setCover(cover);
        document.setIntro(intro);
        document.setFileUrl(fileUrl);
        document.setFileExt(UploadUtils.getFileExt(fileUrl));
        document.setFileSize(TKConvert.toLong(request.getParameter("fileSize")));
        document.setUserId(manager.getUserId());
        document.setUserName(manager.getManagerName());
        document.setPrice(TKConvert.toInteger(request.getParameter("price")) * 100);
        document.setLevelId(TKConvert.toInteger(request.getParameter("levelId")));
        document.setDownCount(TKConvert.toInteger(request.getParameter("downCount")));
        document.setViewCount(TKConvert.toInteger(request.getParameter("viewCount")));
        document.setLikeCount(TKConvert.toInteger(request.getParameter("likeCount")));
        document.setIsElite(TKConvert.toInteger(request.getParameter("isElite")));
        document.setIsTop(TKConvert.toInteger(request.getParameter("isTop")));
        document.setStatus(0);
        //判断图片有没有修改
        if (!TKString.isEmpty(document.getCover())) {
            //原图
            String oldPath = document.getCover();
            //新图
            if (oldPath.contains("/temps/")) {
                String newPath = String.format("%s/%s", UploadConfig.uploadCoverThumb, oldPath.substring(oldPath.indexOf("/temps/") + 7));
                logger.info("oldPath:" + oldPath);
                logger.info("newPath:" + newPath);
                ImageUtils.zoomWithCut(UploadConfig.uploadRoot + oldPath, UploadConfig.uploadRoot + newPath, 400, 280);
                document.setCover(newPath);
            }
        }
        return toAjax(documentService.insert(document));
    }

    @Permissions("document:edit")
    @GetMapping("/edit.html")
    public String edit(HttpServletRequest request, ModelMap mmap) {
        int id = TKConvert.toInteger(request.getParameter("id"));
        if (id < 1) return error404;
        Document document = documentService.get(id);
        if (document == null) return error404;
        MemberType memberType = new MemberType();
        memberType.setStatus(0);
        List<MemberType> members = memberTypeService.getList(memberType,null);
        mmap.put("document", document);
        mmap.put("types", DocumentType.values());
        mmap.put("members", members);
        return "document/document-edit";
    }

    @Permissions("document:edit")
    @PostMapping("/edit.json")
    @Log(title = "编辑资料保存", businessType = BusinessType.UPDATE)
    @ResponseBody
    public AjaxResult edit(HttpServletRequest request) {
        int id = TKConvert.toInteger(request.getParameter("id"));
        if (id < 1) return error("缺少参数id");
        DocumentDetail document = documentService.get(id);
        if (document == null) return error("找不到指定id的资料");
        int categoryId = TKConvert.toInteger(request.getParameter("categoryId"));
        if (categoryId < 1) return error("请选择类别");
        Category category = categoryService.get(categoryId);
        if (category == null) return error("类别categoryId有误");
        String fileUrl = TKString.trim(request.getParameter("fileUrl"));
        if (TKString.isEmpty(fileUrl)) return error("请输入文件地址或上传");
        String title = TKString.trim(request.getParameter("title"));
        if (TKString.isEmpty(title)) return error("请输入文件名");
        String cover = TKString.trim(request.getParameter("cover"));
        if (TKString.isEmpty(cover)) return error("请输入封面地址或上传");
        String intro = TKString.trim(request.getParameter("intro"));
        if (TKString.isEmpty(intro)) return error("请输入资料简介");
        document.setTypeId(TKConvert.toInteger(request.getParameter("typeId")));
        document.setCategoryId(category.getCategoryId());
        document.setCategoryName(category.getCategoryName());
        document.setSubjectId(category.getSubjectId());
        document.setFileUrl(fileUrl);
        document.setFileExt(UploadUtils.getFileExt(fileUrl));
        document.setFileSize(TKConvert.toLong(request.getParameter("fileSize")));
        document.setTitle(title);
        document.setCover(cover);
        document.setIntro(intro);
        document.setTags(TKString.trim(request.getParameter("tags")));
        document.setPrice(TKConvert.toInteger(request.getParameter("price")) * 100);
        document.setLevelId(TKConvert.toInteger(request.getParameter("levelId")));
        document.setDownCount(TKConvert.toInteger(request.getParameter("downCount")));
        document.setViewCount(TKConvert.toInteger(request.getParameter("viewCount")));
        document.setLikeCount(TKConvert.toInteger(request.getParameter("likeCount")));
        document.setIsElite(TKConvert.toInteger(request.getParameter("isElite")));
        document.setIsTop(TKConvert.toInteger(request.getParameter("isTop")));
        //判断图片有没有修改
        if (!TKString.isEmpty(document.getCover())) {
            //原图
            String oldPath = document.getCover();
            //新图
            if (oldPath.contains("/temps/")) {
                String newPath = String.format("%s/%s", UploadConfig.uploadCoverThumb, oldPath.substring(oldPath.indexOf("/temps/") + 7));
                logger.info("oldPath:" + oldPath);
                logger.info("newPath:" + newPath);
                ImageUtils.zoomWithCut(UploadConfig.uploadRoot + oldPath, UploadConfig.uploadRoot + newPath, 400, 280);
                document.setCover(newPath);
            }
        }
        //已审核状态文件修改
        if (!document.getStatus().equals(0)) {
            //判断文件有没有修改
            if (!TKString.isEmpty(document.getFileUrl())) {
                //原
                String oldPath = document.getFileUrl();
                //新
                if (oldPath.contains("/temps/")) {
                    String newPath = String.format("%s/%s", UploadConfig.uploadFileFolder, oldPath.substring(oldPath.indexOf("/temps/") + 7));
                    if (!FileUtils.copyFile(UploadConfig.uploadRoot + oldPath, UploadConfig.uploadRoot + newPath)) {
                        logger.error("复制文件失败：" + oldPath);
                        return error("文件保存失败,请联系管理员");
                    }
                    document.setFileUrl(newPath);
                }
            }
        }
        return toAjax(documentService.update(document));
    }


    /**
     * 固顶操作
     */
    @PostMapping("/top/clicked.json")
    @Log(title = "修改文库固顶", businessType = BusinessType.UPDATE)
    @ResponseBody
    public AjaxResult top(HttpServletRequest request) {
        int id = TKConvert.toInteger(request.getParameter("id"));
        int isTop = TKConvert.toInteger(request.getParameter("isTop"), 0);
        if (id < 1 || isTop > 1 || isTop < 0) return error("参数异常");
        DocumentDetail document = documentService.get(id);
        if (document == null) return error("未找到指定id资料，id=" + id);
        document.setIsTop(isTop);
        return toAjax(documentService.update(document));
    }

    /**
     * 推荐操作
     */
    @PostMapping("/elite/clicked.json")
    @Log(title = "修改文库推荐", businessType = BusinessType.UPDATE)
    @ResponseBody
    public AjaxResult elite(HttpServletRequest request) {
        int id = TKConvert.toInteger(request.getParameter("id"));
        int isElite = TKConvert.toInteger(request.getParameter("isElite"), 0);
        if (id < 1 || isElite > 1 || isElite < 0) return error("参数异常");
        DocumentDetail document = documentService.get(id);
        if (document == null) return error("未找到指定id资料，id=" + id);
        document.setIsElite(isElite);
        return toAjax(documentService.update(document));
    }

    @Permissions("document:remove")
    @Log(title = "删除资料", businessType = BusinessType.DELETE)
    @PostMapping("/remove.json")
    @ResponseBody
    public AjaxResult remove(HttpServletRequest request) {
        int id = TKConvert.toInteger(request.getParameter("id"));
        DocumentDetail document = documentService.get(id);
        if (document == null) return error("未找到指定id资料，id=" + id);
        if (document.getStatus().equals(1)) return error("审核通过资料不能删除");
        int row = documentService.delete(document.getId());
        if (row > 0) {
            //删除审核关联表
            approalService.deleteByInfoId(document.getId(), ModuleType.DOCUMENT.ordinal());
            //同步删除文件
            FileUtils.deleteFile(UploadConfig.uploadRoot + document.getCover());
            FileUtils.deleteFile(UploadConfig.uploadRoot + document.getFileUrl());
        }
        return toAjax(row);
    }
}
